package com.android.fragmentdemo.defineviewgroup
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup
import androidx.core.view.get
import com.android.fragmentdemo.R

class AutoWrapViewGroup @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : ViewGroup(context, attributeSet) {
    private var offsetX = 0
    private var offsetY = 0
    private var totalHeight = 0
    private var marginTop = context.resources.getDimension(R.dimen.dp_10).toInt()
    private var marginStart = context.resources.getDimension(R.dimen.dp_10).toInt()

    private val mapRect by lazy {
        mutableMapOf<Int, Rect>()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        offsetX = 0
        offsetY = 0
        totalHeight = 0
        for (i in 0.until(childCount)) {
            val child = get(i)
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0)
            val mWidth = child.measuredWidth
            val mHeight = child.measuredHeight
            Log.d(TAG, "mHeight:${mHeight}")
            if (offsetX + mWidth > measuredWidth) {
                offsetX = 0
                offsetY += marginTop + mHeight
                totalHeight += marginTop + mHeight
            } else {
                if (i == 0) {
                    totalHeight += offsetY + mHeight
                }
            }
            val rect = mapRect[i] ?: Rect()
            rect.set(offsetX, offsetY, offsetX + mWidth, offsetY + mHeight)
            mapRect[i] = rect
            offsetX += mWidth + marginStart
        }
        setMeasuredDimension(
            MeasureSpec.getSize(widthMeasureSpec),
            MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY)
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        for (i in 0.until(childCount)) {
            mapRect[i]?.let {
                val child = get(i)
                child.layout(it.left, it.top, it.right, it.bottom)
            }
        }
    }

    override fun generateDefaultLayoutParams(): LayoutParams {
        return MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT, MarginLayoutParams.WRAP_CONTENT)
    }

    companion object {
        const val TAG = "AutoWrapViewGroup"
    }
}